package handler

import (
    "context"
    "gonaio_base/function"
    "gonaio_base/rpc/proto_user"
    "gonaio_user_service/service"
)

type User struct {
}

var userInstance = new(User)

func NewUser() *User {
    return userInstance
}

func (*User) Reg(ctx context.Context, request *proto_user.UserRegRequest, response *proto_user.UserRegResponse) error {
    err := service.NewUser().Reg(request.GetUsername(), request.GetPassword())
    if err != nil {
        response.Code = 1
        response.Msg = err.Error()
        return nil
    }
    return err
}

func (*User) List(ctx context.Context, request *proto_user.UserListRequest, response *proto_user.UserListResponse) error {
    list, count, err := service.NewUser().ListData(request.GetPage(), request.GetLimit())
    response.Count = count
    for _, item := range list {
        listItem := &proto_user.UserModel{
            ID:       item.ID,
            Username: item.Username,
            Password: item.Password,
            Name:     item.Name,
            Sex:      item.Sex,
            Age:      item.Age,
        }
        listItem.CreatedAt = bfunction.Time2String(item.CreatedAt)
        listItem.UpdatedAt = bfunction.Time2String(item.UpdatedAt)
        if item.DeletedAt != nil {
            listItem.DeletedAt = bfunction.Time2StringX(item.DeletedAt)
        }
        response.List = append(response.List, listItem)
    }
    return err
}
